//
//  OrderDetaliViewController.m
//  WeiWeiHaircut
//
//  Created by 超群 on 15/10/16.
//  Copyright © 2015年 超群. All rights reserved.
//

#import "OrderDetaliViewController.h"
#import "OrderDetailNumCell.h"
#import "OrderDetailCommomTableViewCell.h"
#import "OrderDetailImageCell.h"
#import "PayMoneyViewController.h"
#import "PreferentialController.h"
#import "DistributionWayViewController.h"

#import "QZAddressController.h"
#import "QZAddressModel.h"
#import "QZShopCarModel.h"
#import "QZOrderModel.h"
@interface OrderDetaliViewController () <UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *allModelNew;

@property (nonatomic, assign) BOOL isCreateOrder;

@property (nonatomic, assign) NSInteger address_ID;

@end

@implementation OrderDetaliViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self titleWithSting:@"确认订单"];
    [self buildTableViewUI];
    [self addBtnOnNavWithTitle:@"购物车" andImageName:@"返回" andTarget:self andAction:@selector(backAction) andFrame:CGRectMake(0, 0, 80, 20) andDirection:left];
    
    self.allModelNew.text = [NSString stringWithFormat:@"%.2f",_allMoney];
    self.allModelNew.textColor = purColor2;
  
    
    [self getDrfuAddress];
}
-(void)getDrfuAddress{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Address.GetgetAddressIsDefalut"];
    
    [self.request QZRequest_POST:url parameters:@{@"user_id":[QZUserInfo userId]} tagNSString:@"获取默认地址" stopRequest:YES isSerializer:NO isCache:YES];
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)buildTableViewUI
{
    self.tableView.delegate         = self;
    self.tableView.dataSource       = self;
    self.tableView.separatorStyle   = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor  = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderDetailNumCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([OrderDetailNumCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderDetailCommomTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([OrderDetailCommomTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderDetailImageCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([OrderDetailImageCell class])];
    
    self.payButton.backgroundColor = SBpurpleColor;
}

#pragma mark - tableheaderView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* headerTitleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    [headerTitleView setBackgroundColor:[UIColor whiteColor]];
    headerTitleView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    return headerTitleView;
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3+self.settleAccounts.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 85;
    }
    if (indexPath.section !=0 && indexPath.section !=3+self.settleAccounts.count-1 && indexPath.section !=3+self.settleAccounts.count-2) {
        return 82;
    }
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    
    
    if (indexPath.section == 0) {
        
        if (_isCreateOrder) {
            [iToast makeText:@"订单已生成,无法修改地址"];
            return;
        }
        OrderDetailNumCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        QZAddressController *addressVc = [[QZAddressController alloc] init];
        
        __weak typeof (self) weakSelf = self;
        addressVc.changeAddress = ^(QZAddressModel *model){
            
            cell.name.text  = [NSString stringWithFormat:@"%@",model.receiver];
            cell.phone.text = [NSString stringWithFormat:@"电话:%@",model.tel];
            cell.address.text=[NSString stringWithFormat:@"收货地址:%@%@",model.addressbie,model.address];
            weakSelf.address_ID = model.id;
        };
        
        [self.navigationController pushViewController:addressVc animated:YES];
    }
    
    if (indexPath.section == 3+self.settleAccounts.count-2) {
        
        PreferentialController *prefrentialVc = [[PreferentialController alloc] init];
        OrderDetailCommomTableViewCell* cell  = [tableView cellForRowAtIndexPath:indexPath];
        prefrentialVc.SelectPreferentail      = ^(id objec){
            
            cell.contentLabel.text = objec;
        };
        [self.navigationController pushViewController:prefrentialVc animated:YES];
        
    }
    
    if (indexPath.section == 3 + self.settleAccounts.count-1) {
        OrderDetailCommomTableViewCell* cell        = [tableView cellForRowAtIndexPath:indexPath];
        DistributionWayViewController *distribution = [[DistributionWayViewController alloc] init];
        distribution.SelectPreferentail             = ^(id objec){
            cell.contentLabel.text = objec;
        };
        [self.navigationController pushViewController:distribution animated:YES];
    }
}

#pragma mark - tableView datasource
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        OrderDetailNumCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OrderDetailNumCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    if (indexPath.section !=0 && indexPath.section !=3+self.settleAccounts.count-1 && indexPath.section !=3+self.settleAccounts.count-2) {
        OrderDetailImageCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OrderDetailImageCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.shopModel = self.settleAccounts[indexPath.section-1];
        return cell;
    }

    if (indexPath.section >=3+self.settleAccounts.count-2) {
            OrderDetailCommomTableViewCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OrderDetailCommomTableViewCell class]) forIndexPath:indexPath];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.section == 3+self.settleAccounts.count-2) {
            cell.titleLabel.text = @"商家优惠:";
            cell.contentLabel.text = @"满100减20";
        }
        if (indexPath.section == 3+self.settleAccounts.count-1){
            cell.titleLabel.text = @"配送方式:";
            cell.contentLabel.text = @"快递包邮";
        }
        return cell;
        
    }

    return nil;

}



#pragma mark- 立即支付按钮
- (IBAction)payTap:(UIButton *)sender {
    
    _isCreateOrder = YES;
    
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"ProdOrder.GetProdOrderAdd"];
    
    NSMutableArray *detail = [NSMutableArray array];
    
    for (QZShopCarModel *model in _settleAccounts) {
        [detail addObject:@(model.detailId)];
    }
    if (!self.address_ID) {
        [[iToast makeText:@"请添加收货地址"] show];
        return;
    }
    NSNumber *user_id = [NSNumber numberWithInteger:[[QZUserInfo userId] integerValue]];
    
    NSDictionary *dic = @{
                          @"address_id":@(self.address_ID),
                          @"user_id":user_id,
                          @"details_ids":detail
                          };
    
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"结算" stopRequest:YES isSerializer:NO isCache:NO];
    
    

}


-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag{

    if ([tag isEqualToString:@"结算"]) {
        if ([value[@"data"][@"status"] integerValue] == 100) {
            QZOrderModel *model = [[QZOrderModel alloc] initWithDictionary:value[@"data"][@"data"] error:nil];
            
            
            PayMoneyViewController  * payVC = [[PayMoneyViewController alloc]initWithNibName:nil bundle:nil];
            payVC.model = model;
            [self.navigationController pushViewController:payVC animated:YES];
            
        }
    }

    
    if ([tag isEqualToString:@"获取默认地址"]) {
        
        QZAddressModel *model = [[QZAddressModel alloc] initWithDictionary:value[@"data"] error:nil];
        if(!model) return;
        NSIndexPath *indexPath =[NSIndexPath indexPathForRow:0 inSection:0];
        OrderDetailNumCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.name.text = model.receiver;
        cell.phone.text = model.tel;
        cell.address.text = [NSString stringWithFormat:@"%@%@",model.addressbie,model.address];
        _address_ID = model.id;
    }
}

-(void)dealloc{
    
    NSLog(@"---------------------%s",__FUNCTION__);
    
}
@end
